package org.langqiao.thread;

//½�ο¼£º
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;

/**
 * need jdk 1.5.0 up
 */
public class Clock extends JFrame{

 /**
  * 
  */
 private static final long serialVersionUID = 1L;

 public Clock(){
  this.setSize(600,500);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  timer=new Timer();
  task=new TimerTask(){
   public void run(){
    if(pause){
     return;
    }
    synchronized(lock){
     second++;
    }
    Clock.this.repaint();
   }
  };
  this.addKeyListener(new KeyListener(){

   @Override
   public void keyTyped(KeyEvent e) {
   }

   @Override
   public void keyPressed(KeyEvent e) {
   }

   @Override
   public void keyReleased(KeyEvent e) {
    int code=e.getKeyCode();
    System.out.println(KeyEvent.VK_SPACE+":"+code);
    if(KeyEvent.VK_SPACE==code){
     pause=!pause;
    }
   }
   
  });
 }
 
 public void setVisible(boolean flag){
  super.setVisible(flag);
  timer.schedule(task, 0, 1000);
 }
 
 public void paint(Graphics g){
  int angle;
  synchronized(lock){
   second%=60;
   angle=90-second*6;
  }
  System.out.println(second);
  g.clearRect(0, 0, getWidth(), getHeight());
  Graphics2D g2=(Graphics2D) g;
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g2.setPaint(Color.RED);
  Ellipse2D dial=new Ellipse2D.Double(100,100,200,200);
  g2.draw(dial);
  System.out.println(angle);
  Arc2D needle=new Arc2D.Double(100, 100, 200, 200, angle, 0, Arc2D.PIE);
  g2.setPaint(Color.GREEN);
  g2.draw(needle);
 }
 
 private TimerTask task;
 private Timer timer;
 private Integer second=0;
 private Object lock=new Object();
 private boolean pause=true;
 
 public static void main(String... args){
  EventQueue.invokeLater(new Runnable(){
   public void run(){
    new Clock().setVisible(true);
   }
  });
 }
}